package com.ge.med.cchelper.popup.job;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import com.ge.med.cchelper.Constants;
import com.ge.med.cchelper.bean.CSession;
import com.ge.med.cchelper.bean.Response;
import com.ge.med.cchelper.util.LogUtil;
import com.ge.med.cchelper.util.ReourceHelper;
import com.ge.med.cchelper.util.SSLhelper;
import com.ge.med.cchelper.util.TextHelper;

public class LsCheckoutJob extends BaseJob{
	private String lsco;
	private Pattern pattern;
	public LsCheckoutJob(String name,CSession session) {
		super(name);
		lsco = session.getCleartool()+" lsco -cview -me -avobs -sho";
		pattern = Pattern.compile("(/vobs/.+)");
	}

	@Override
	protected IStatus start(IProgressMonitor arg0) {
		IProject currentProject = ReourceHelper.getProject();
		String vobPath = "/" +currentProject.getProject().getName()+ "/" + Constants.VOB;
		String confdir =  currentProject.getLocation().toOSString();
		
		
		SSLhelper sslHelper = new SSLhelper(csession);

		// checkout source
		Response res0 = sslHelper.executeCT(lsco);
		
		int found = 0;
			//lsco -cview
			String lsContent = res0.getContent().toString().trim();
			StringBuilder allCheckOutFiles= new StringBuilder("");
			
			Matcher matcher = pattern.matcher(lsContent);
			while (matcher.find()) {
				String realPath = matcher.group();
				if(!realPath.trim().equals("")){
						String checkOutFileName = realPath.replace("/vobs", vobPath);
						allCheckOutFiles.append(checkOutFileName+"\r\n");
						found++;
				}
			}
			

				try {
					TextHelper.clear(confdir+File.separator+TextHelper.CHECKOUT_FILE);	
				    TextHelper.writeText(confdir+File.separator+TextHelper.CHECKOUT_FILE, allCheckOutFiles.toString());
				} catch (Exception e) {
					e.printStackTrace();
					LogUtil.err("write checkout flag failed."
							+ e.getMessage());
					return Status.CANCEL_STATUS;
				}
				
				try {
					currentProject.refreshLocal(
							IProject.DEPTH_INFINITE, null);
				} catch (CoreException e1) {
					e1.printStackTrace();
					LogUtil.err("refresh failed." + e1.getMessage());
				}
			
		
		
		return Status.OK_STATUS;
	}

}
